<!DOCTYPE html>
<html>
<head>
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?d890b1f16fb364253e79c5bb20225c3a";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


    

    

    
<!-- Baidu Tongji -->
<script>var _hmt = _hmt || []</script>
<script async src="//hm.baidu.com/hm.js?busuanzi_value_site_uv"></script>
<!-- End Baidu Tongji -->




    <meta charset="utf-8">
    <meta name="baidu-site-verification" content="FYMCShbUK8" />
    <meta name="baidu-site-verification" content="ZYRF7OxQRW" />
    <meta name="baidu-site-verification" content="cHSqtjI0PN" />
    <meta name="baidu-site-verification" content="cHSqtjI0PN" />
    <meta name="baidu-site-verification" content="cHSqtjI0PN" />
    
    
    <link rel="canonical" href="https://hhardyy.com/2018/02/02/js中的事件冒泡/">
    
    
    <title>js中的事件冒泡 | 小方块 - hhardyy.com | 复杂的坑+归其原理+了解实现规则===解决？解决成功：加油解决成功;</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#958e93">
    
    
    <meta name="keywords" content="javascript,事件冒泡,event,验证IE,call(),事件捕获">
    <meta name="description" content="事件是javascript中的核心内容之一，在对事件的应用中不可避免的要涉及到一个重要的概念，那就是事件冒泡，在了解事件冒泡之前，先了解一下事件流">
<meta name="keywords" content="javascript,事件冒泡,event,验证IE,call(),事件捕获">
<meta property="og:type" content="article">
<meta property="og:title" content="js中的事件冒泡">
<meta property="og:url" content="http://yoursite.com/2018/02/02/js中的事件冒泡/index.html">
<meta property="og:site_name" content="小方块 - hhardyy.com">
<meta property="og:description" content="事件是javascript中的核心内容之一，在对事件的应用中不可避免的要涉及到一个重要的概念，那就是事件冒泡，在了解事件冒泡之前，先了解一下事件流">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://yoursite.com/images/maopaoImg/maopao.jpg">
<meta property="og:image" content="http://yoursite.com/images/maopaoImg/1.JPG">
<meta property="og:image" content="http://yoursite.com/images/maopaoImg/2.JPG">
<meta property="og:image" content="http://yoursite.com/images/maopaoImg/3.JPG">
<meta property="og:image" content="http://yoursite.com/images/maopaoImg/4.JPG">
<meta property="og:image" content="http://yoursite.com/images/maopaoImg/6.JPG">
<meta property="og:image" content="http://yoursite.com/images/maopaoImg/6.JPG">
<meta property="og:updated_time" content="2020-01-13T15:20:18.388Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="js中的事件冒泡">
<meta name="twitter:description" content="事件是javascript中的核心内容之一，在对事件的应用中不可避免的要涉及到一个重要的概念，那就是事件冒泡，在了解事件冒泡之前，先了解一下事件流">
<meta name="twitter:image" content="http://yoursite.com/images/maopaoImg/maopao.jpg">
    
        <link rel="alternate" type="application/atom+xml" title="小方块 - hhardyy.com" href="/atom.xml">
    
    <link rel="shortcut icon" href="/hardyfavicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/paulGraham.jpg)">
      <div class="brand" style="background-color:#4154b2">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">BingZhenhuang</h5>
          <a href="mailto:huangbingzhen@hhardyy.com" title="huangbingzhen@hhardyy.com" class="mail">huangbingzhen@hhardyy.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                所有文章
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/HHardyy" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://gitee.com/hhardyy" target="_blank" >
                <i class="icon icon-lg icon-cloud"></i>
                Gitee
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://juejin.im/user/59a26f926fb9a02487553b04"  >
                <i class="icon icon-lg icon-pencil"></i>
                掘金-圳
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://segmentfault.com/u/hhardyy"  >
                <i class="icon icon-lg icon-comments"></i>
                Segmentfault
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://codepen.io/HHardyy/" target="_blank" >
                <i class="icon icon-lg icon-codepen"></i>
                Codepen
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.freecodecamp.cn/hhardyy" target="_blank" >
                <i class="icon icon-lg icon-leaf"></i>
                Freecodecamp
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/友情链接"  >
                <i class="icon icon-lg icon-link"></i>
                友链
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">js中的事件冒泡</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">js中的事件冒泡</h1>
        <h5 class="subtitle">
            
                <time datetime="2018-02-02T09:02:50.000Z" itemprop="datePublished" class="page-time">
  2018-02-02
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#什么是事件流："><span class="post-toc-number">1.</span> <span class="post-toc-text">什么是事件流：</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#什么是事件冒泡："><span class="post-toc-number">2.</span> <span class="post-toc-text">什么是事件冒泡：</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#事件冒泡的影响："><span class="post-toc-number">3.</span> <span class="post-toc-text">事件冒泡的影响：</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#阻止冒泡："><span class="post-toc-number">4.</span> <span class="post-toc-text">阻止冒泡：</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#阻止冒泡的方法：在当前要阻止的事件冒泡函数中调用event-cancelBubble-true"><span class="post-toc-number">5.</span> <span class="post-toc-text">阻止冒泡的方法：在当前要阻止的事件冒泡函数中调用event.cancelBubble=true;</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#事件冒泡的用法："><span class="post-toc-number">6.</span> <span class="post-toc-text">事件冒泡的用法：</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#另外两种阻止事件冒泡的方法和用法"><span class="post-toc-number">7.</span> <span class="post-toc-text">另外两种阻止事件冒泡的方法和用法</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Event对象"><span class="post-toc-number">8.</span> <span class="post-toc-text">Event对象</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Event对象的兼容："><span class="post-toc-number">9.</span> <span class="post-toc-text">Event对象的兼容：</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Event对象下获取鼠标位置："><span class="post-toc-number">10.</span> <span class="post-toc-text">Event对象下获取鼠标位置：</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#事件函数"><span class="post-toc-number">11.</span> <span class="post-toc-text">事件函数</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#IE、谷歌和火狐下的ev"><span class="post-toc-number">12.</span> <span class="post-toc-text">IE、谷歌和火狐下的ev</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#ev用的时候-兼容处理-："><span class="post-toc-number">13.</span> <span class="post-toc-text">ev用的时候(兼容处理)：</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#查看事件："><span class="post-toc-number">14.</span> <span class="post-toc-text">查看事件：</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#同时联想到一些可能用得上的事件，算了也写在这里吧："><span class="post-toc-number">15.</span> <span class="post-toc-text">同时联想到一些可能用得上的事件，算了也写在这里吧：</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#最后再来一个判断是否IE浏览器的方法"><span class="post-toc-number">16.</span> <span class="post-toc-text">最后再来一个判断是否IE浏览器的方法</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#绑定多个事件"><span class="post-toc-number">17.</span> <span class="post-toc-text">绑定多个事件</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#那么什么是事件捕获："><span class="post-toc-number">18.</span> <span class="post-toc-text">那么什么是事件捕获：</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#call-方法"><span class="post-toc-number">19.</span> <span class="post-toc-text">call()方法</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#最后封一个绑定多个事件的方法，蛮实用"><span class="post-toc-number">20.</span> <span class="post-toc-text">最后封一个绑定多个事件的方法，蛮实用</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#事件绑定的取消"><span class="post-toc-number">21.</span> <span class="post-toc-text">事件绑定的取消</span></a></li></ol>
        </nav>
    </aside>
    
<article id="post-js中的事件冒泡"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">js中的事件冒泡</h1>
        <div class="post-meta">
            <time class="post-time" title="2018-02-02 17:02:50" datetime="2018-02-02T09:02:50.000Z"  itemprop="datePublished">2018-02-02</time>

            


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p>事件是javascript中的核心内容之一，在对事件的应用中不可避免的要涉及到一个重要的概念，那就是事件冒泡，在了解事件冒泡之前，先了解一下事件流<br><a id="more"></a></p>
<p><iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=496040491&auto=0&height=66"></iframe></p>
<h3 id="什么是事件流："><a href="#什么是事件流：" class="headerlink" title="什么是事件流："></a>什么是事件流：</h3><p>从window到document到h1、p、h2、form…等。也就是html元素触发事件，那么这个事件就会在DOM中的触发节点和根节点之间按照一定的顺序传播，所有经过的节点都会接收到被触发的事件，这个传播过程被称之为事件流。</p>
<h3 id="什么是事件冒泡："><a href="#什么是事件冒泡：" class="headerlink" title="什么是事件冒泡："></a>什么是事件冒泡：</h3><p>就是当一个元素触发一个事件，事件会像是水泡一样，从触发元素向它的所有父节点传播，一直到根节点都会接收到此事件，如果父元素中注册了相应的事件处理函数，那么尽管事件在子节点触发的，在父元素上注册的事件处理函数同样会被触发。<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/images/maopaoImg/maopao.jpg" alt="“冒泡大哥”" title="">
                </div>
                <div class="image-caption">“冒泡大哥”</div>
            </figure><br>例如:我创建了三个div，给最里头的div加上点击事件（准确的说是给元素加上事件处理函数）<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/images/maopaoImg/1.JPG" alt="“html代码”" title="">
                </div>
                <div class="image-caption">“html代码”</div>
            </figure><br>预览效果：<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/images/maopaoImg/2.JPG" alt="“预览效果”" title="">
                </div>
                <div class="image-caption">“预览效果”</div>
            </figure><br>里头的div分别绑定了click事件，然后点击最里头的div3，就会依次弹出div3,div2,div1，这就是事件冒泡，原理是当div3执行完事件处理函数之后，事件就会向父级传播，像冒泡一样所以叫事件冒泡。</p>
<p>假设把div2的事件注释掉<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// dIv2.addEventListener('click',fn);</span></div></pre></td></tr></table></figure></p>
<p>依然可以弹出div1和div3,事实上div2身上也接收到了默认冒泡事件，只是没有给它事件处理函数，也就是没有告诉它接收到事件之后做什么，所以即使父级不绑定执行的函数，冒泡也默认存在，这就是默认存在的事件冒泡机制。</p>
<h3 id="事件冒泡的影响："><a href="#事件冒泡的影响：" class="headerlink" title="事件冒泡的影响："></a>事件冒泡的影响：</h3><p>直接举个例子：比如下拉菜单（此处有点丑）<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/images/maopaoImg/3.JPG" alt="“html代码”" title="">
                </div>
                <div class="image-caption">“html代码”</div>
            </figure><br>效果图：<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/images/maopaoImg/4.JPG" alt="“预览效果”" title="">
                </div>
                <div class="image-caption">“预览效果”</div>
            </figure><br>需求是点击按钮菜单显示，点击文档区域菜单隐藏，js代码：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> oBtn=<span class="built_in">document</span>.getElementById(<span class="string">"btn"</span>);</div><div class="line"><span class="keyword">var</span> dIv=<span class="built_in">document</span>.getElementById(<span class="string">"div"</span>);</div><div class="line"></div><div class="line">oBtn.addEventListener(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">	dIv.style.display=<span class="string">"block"</span>;</div><div class="line">&#125;);</div><div class="line"><span class="built_in">document</span>.addEventListener(<span class="string">'click'</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">	dIv.style.display=<span class="string">"none"</span>;</div><div class="line">&#125;);</div></pre></td></tr></table></figure></p>
<p>那么问题来了，文档还没加上点击事件的时候，按钮点击菜单可以显示，文档加上点击事件之后，按钮点击就点不出菜单了。</p>
<p>这时候给文档点击加上延时执行定时器：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">document</span>.addEventListener(<span class="string">'click'</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">        dIv.style.display=<span class="string">"none"</span>;</div><div class="line">    &#125;, <span class="number">1000</span>);</div><div class="line">&#125;);</div></pre></td></tr></table></figure></p>
<p>这时候就可以正常点击。</p>
<p>原理：按钮的点击事件点击之后将事件传递到了document父级，所以按钮点击完成之后由于document也绑定了事件处理函数“菜单隐藏”，所以就直接执行了。</p>
<h3 id="阻止冒泡："><a href="#阻止冒泡：" class="headerlink" title="阻止冒泡："></a>阻止冒泡：</h3><p>如果在某个地方不想让事件冒泡可以单独阻止，毕竟冒泡事件带来的好处也很大，比如直接触发文档流下的许多元素绑定的事件处理函数</p>
<h3 id="阻止冒泡的方法：在当前要阻止的事件冒泡函数中调用event-cancelBubble-true"><a href="#阻止冒泡的方法：在当前要阻止的事件冒泡函数中调用event-cancelBubble-true" class="headerlink" title="阻止冒泡的方法：在当前要阻止的事件冒泡函数中调用event.cancelBubble=true;"></a>阻止冒泡的方法：在当前要阻止的事件冒泡函数中调用event.cancelBubble=true;</h3><p>例如将上面的js修改为：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">oBtn.addEventListener(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">ev</span>)</span>&#123;</div><div class="line">    <span class="keyword">var</span> ev=ev||event;</div><div class="line">    ev.cancelBubble=<span class="literal">true</span>;<span class="comment">//阻止当前对象的当前事件的冒泡</span></div><div class="line">    dIv.style.display=<span class="string">"block"</span>;</div><div class="line">&#125;);</div><div class="line"><span class="built_in">document</span>.addEventListener(<span class="string">'click'</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    dIv.style.display=<span class="string">"none"</span>;</div><div class="line">&#125;);</div></pre></td></tr></table></figure></p>
<p>下拉菜单就可以正常跑起来了（虽丑），那么问题又来了，假如按钮身上同时还绑定了一个mouseover的事件，上面设置的阻止冒泡就不生效了，这时候也需要给mouseover事件阻止冒泡，也就是冒泡只能单独阻止。</p>
<h3 id="事件冒泡的用法："><a href="#事件冒泡的用法：" class="headerlink" title="事件冒泡的用法："></a>事件冒泡的用法：</h3><p>也直接举例子，比如分享功能：<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/images/maopaoImg/6.JPG" alt="“html代码”" title="">
                </div>
                <div class="image-caption">“html代码”</div>
            </figure><br>效果图：<br><figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/images/maopaoImg/6.JPG" alt="“预览效果”" title="">
                </div>
                <div class="image-caption">“预览效果”</div>
            </figure><br>需求：鼠标经过的时候从左边出来，鼠标离开的时候只显示分享到部分，传统的做法是分别加上mouseover、mouseout,<br>但是用冒泡的做法是直接给div去做就行了：</p>
<p>js代码：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> oDiv=<span class="built_in">document</span>.getElementById(<span class="string">"div1"</span>);</div><div class="line">oDiv.addEventListener(<span class="string">'mouseover'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="keyword">this</span>.style.left=<span class="string">"0px"</span>;</div><div class="line">&#125;);</div><div class="line">oDiv.addEventListener(<span class="string">'mouseout'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="keyword">this</span>.style.left=<span class="string">"-100px"</span>;</div><div class="line">&#125;);</div></pre></td></tr></table></figure></p>
<p>当然，阻止事件冒泡的方法还有两种：</p>
<h3 id="另外两种阻止事件冒泡的方法和用法"><a href="#另外两种阻止事件冒泡的方法和用法" class="headerlink" title="另外两种阻止事件冒泡的方法和用法"></a>另外两种阻止事件冒泡的方法和用法</h3><p>方法一：event.stopPropagation();<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">$(<span class="string">"xxx"</span>).click(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    event.stopPropagation();</div><div class="line">&#125;)</div></pre></td></tr></table></figure></p>
<p>方法二：event.target<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">$(<span class="built_in">document</span>).ready(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    $(<span class="string">"#xxx"</span>).click(<span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">        <span class="keyword">if</span>(event.target==<span class="keyword">this</span>)&#123;</div><div class="line">            $(<span class="string">"#xxx"</span>).xxx</div><div class="line">        &#125;</div><div class="line">    &#125;)</div><div class="line">&#125;)</div></pre></td></tr></table></figure></p>
<p>顺便介绍一下event对象</p>
<h3 id="Event对象"><a href="#Event对象" class="headerlink" title="Event对象"></a>Event对象</h3><p>当一个事件发生的时候，和当前这个对象发生的这个事件有关的一些详细的信息都会被临时保存到一个指定地方—event对象，供需要的时候调用<br>用来获取事件的详细信息。</p>
<h3 id="Event对象的兼容："><a href="#Event对象的兼容：" class="headerlink" title="Event对象的兼容："></a>Event对象的兼容：</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">ev=ev||<span class="built_in">window</span>.event</div></pre></td></tr></table></figure>
<h3 id="Event对象下获取鼠标位置："><a href="#Event对象下获取鼠标位置：" class="headerlink" title="Event对象下获取鼠标位置："></a>Event对象下获取鼠标位置：</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">clientX clientY</div></pre></td></tr></table></figure>
<p>事件对象必须在一个事件调用的函数里面使用才有内容</p>
<h3 id="事件函数"><a href="#事件函数" class="headerlink" title="事件函数"></a>事件函数</h3><p>事件调用的函数，取决于被什么时间调用</p>
<h3 id="IE、谷歌和火狐下的ev"><a href="#IE、谷歌和火狐下的ev" class="headerlink" title="IE、谷歌和火狐下的ev"></a>IE、谷歌和火狐下的ev</h3><p>iE/chrome:event是一个内置全局对象<br>Firefox（同时也是标准下）:事件对象是通过事件函数的第一个参数传入如function fn(ev)====（如果一个函数是被事件调用的，那么这个函数定义的第一个参数就是事件对象）</p>
<h3 id="ev用的时候-兼容处理-："><a href="#ev用的时候-兼容处理-：" class="headerlink" title="ev用的时候(兼容处理)："></a>ev用的时候(兼容处理)：</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> ev=ev||evnt</div></pre></td></tr></table></figure>
<h3 id="查看事件："><a href="#查看事件：" class="headerlink" title="查看事件："></a>查看事件：</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">for</span>(attr <span class="keyword">in</span> ev)&#123;</div><div class="line">    <span class="built_in">console</span>.log(attr+<span class="string">"="</span>+ev[attr])</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="同时联想到一些可能用得上的事件，算了也写在这里吧："><a href="#同时联想到一些可能用得上的事件，算了也写在这里吧：" class="headerlink" title="同时联想到一些可能用得上的事件，算了也写在这里吧："></a>同时联想到一些可能用得上的事件，算了也写在这里吧：</h3><p>onscroll:当滚动条滚动的时候触发<br>onresize:当窗口大小发生改变的时候触发<br>onfocus:获取焦点事件<br>onblur:失去焦点事件<br>focus()：页面打开给指定元素设置焦点…txt.focus();<br>blur()取消指定元素的焦点<br>select()选择指定元素的文本内容(只能操作可交互性的文本内容)</p>
<h3 id="最后再来一个判断是否IE浏览器的方法"><a href="#最后再来一个判断是否IE浏览器的方法" class="headerlink" title="最后再来一个判断是否IE浏览器的方法"></a>最后再来一个判断是否IE浏览器的方法</h3><p>js查看浏览器信息<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">alert(<span class="built_in">window</span>.navigator.userAgent);</div></pre></td></tr></table></figure></p>
<p>验证IE<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span>(<span class="built_in">window</span>.navigator.userAgent.indexOf(<span class="string">'MSIE'</span>)!=<span class="number">-1</span>)&#123;</div><div class="line">       alert(<span class="string">"IE"</span>);</div><div class="line">    &#125;<span class="keyword">else</span>&#123;</div><div class="line">       alert(<span class="string">"不是IE"</span>);</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>那既然写了事件，就多写一些吧（其实这里是因为在这地方突然没网，线上更新不了，用手机开热点手机坏了（已扔下一楼），然后这里顺便扯一些其他的东西）</p>
<h3 id="绑定多个事件"><a href="#绑定多个事件" class="headerlink" title="绑定多个事件"></a>绑定多个事件</h3><p>如果多个部门或者多个人都需要对同一个元素绑定事件<br>A部门绑定click事件A，B部门绑定click事件B，一般如果写成onclick的话，一点击就会覆盖掉另一个部门的东西，解决方案：<br>1、部门之间开发的时候密切沟通好里头的各种命名以及结构数据等，然后将两个事件合并，那么好，两个部门同时的话，两个部门一起交流沟通，好，这时候如果每个部门的需求是每部门再来个事件，行，那就沟通呗，一个星期达成共识，如果需求里头代码多，变量多，那继续沟通呗，好，老板这时候或许已经在想宣告破产之后的情景了。<br>2、绑定多个事件用addEventListener（事件，函数处理方法，true或者false（代表捕获与不捕获）），IE下是attachEvent（on+事件，函数处理方法）</p>
<h3 id="那么什么是事件捕获："><a href="#那么什么是事件捕获：" class="headerlink" title="那么什么是事件捕获："></a>那么什么是事件捕获：</h3><p>捕获机制如果触发的话，事件会从父级元素经过，然后到触发的元素，和冒泡事件不同的是，冒泡是从触发的事件向父级传输</p>
<h3 id="call-方法"><a href="#call-方法" class="headerlink" title="call()方法"></a>call()方法</h3><p>attachEvent绑定的事件，this指向不会指向触发事件的元素，而是window,所以要用到call()方法，例如触发fn函数，写成fn.call();<br>call()方法里头的参数是触发的事件处理函数里头的this指向，如果是多个参数的函数例如fn(obj,attr)，就写成<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">fn.call(<span class="built_in">window</span>,oDiv,<span class="class"><span class="keyword">class</span>)</span>;</div></pre></td></tr></table></figure></p>
<p>这里第一个参数依旧是事件处理函数里头的this指向的window，后面两个参数是传给函数方法的参数。</p>
<h3 id="最后封一个绑定多个事件的方法，蛮实用"><a href="#最后封一个绑定多个事件的方法，蛮实用" class="headerlink" title="最后封一个绑定多个事件的方法，蛮实用"></a>最后封一个绑定多个事件的方法，蛮实用</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">bind</span>(<span class="params">obj,eventName,fn</span>)</span>&#123;</div><div class="line">    <span class="keyword">if</span> (obj.addEventListener) &#123;</div><div class="line">        obj.addEventListener(eventName,fn,<span class="literal">false</span>);</div><div class="line">    &#125;<span class="keyword">else</span>&#123;</div><div class="line">        obj.attachEvent(<span class="string">'on'</span>+eventName, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">             fn.call(obj);</div><div class="line">        &#125;);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="事件绑定的取消"><a href="#事件绑定的取消" class="headerlink" title="事件绑定的取消"></a>事件绑定的取消</h3><p>1、事件绑定形式的取消<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">document</span>.onclick=fun;</div><div class="line"><span class="built_in">document</span>.onclick=<span class="literal">null</span>;</div></pre></td></tr></table></figure></p>
<p>2、通过addEventListener()取消<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">IE下：obj.detachEvent(<span class="string">'onclick'</span>,fun)</div><div class="line">标准下：obj.removeEventListener(事件名称，事件处理函数，是否捕获)</div></pre></td></tr></table></figure></p>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2020-01-13T15:20:18.388Z" itemprop="dateUpdated">2020-01-13 23:20:18</time>
</span><br>


        
        谢谢浏览，我会继续努力的，示例：<a href="/2018/02/02/js中的事件冒泡/" target="_blank" rel="external">http://yoursite.com/2018/02/02/js中的事件冒泡/</a>
        
    </div>
    <footer>
        <a href="http://yoursite.com">
            <img src="/img/avatar.jpg" alt="BingZhenhuang">
            BingZhenhuang
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/call/">call()</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/event/">event</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/javascript/">javascript</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/事件冒泡/">事件冒泡</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/事件捕获/">事件捕获</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/验证IE/">验证IE</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://yoursite.com/2018/02/02/js中的事件冒泡/&title=《js中的事件冒泡》 — 小方块 - hhardyy.com&pic=http://yoursite.com/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://yoursite.com/2018/02/02/js中的事件冒泡/&title=《js中的事件冒泡》 — 小方块 - hhardyy.com&source=事件是javascript中的核心内容之一，在对事件的应用中不可避免的要涉及到一个重要的概念，那就是事件冒泡，在了解事件冒泡之前，先了解一下事件流" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://yoursite.com/2018/02/02/js中的事件冒泡/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《js中的事件冒泡》 — 小方块 - hhardyy.com&url=http://yoursite.com/2018/02/02/js中的事件冒泡/&via=http://yoursite.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://yoursite.com/2018/02/02/js中的事件冒泡/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2018/02/05/IE-chrome-Firefox的鼠标滚轮兼容/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">IE/chrome/Firefox的鼠标滚轮兼容</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2018/01/19/post、get和ajax跨域/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">post、get和ajax跨域</h4>
      </a>
    </div>
  
</nav>



    














</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        🤠 请我喝可乐！
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content" style="width:50%">
        
        <div class="reward-code" style="text-align:center">
            <div style="width:300px;margin:0px auto;">
               <img id="rewardCode" style="width:50%;height:60%;display:block; margin:0px auto;" src="/img/alipay.jpg" alt="支付宝打赏二维码">
               <span style="display:inline-block; margin-bottom:20px;">0.88(支付宝 aliPay)</span>
               <img id="rewardCode" style="width:50%;height:60%;display:block; margin:0px auto;" src="/img/wechat.jpg" alt="微信打赏二维码">
               <span style="display:inline-block;">0.88(微信 weChat)</span>
            </div>
        </div>
    </div>
</div>



</div>

        <script>
!function(e,t,a){function n(){c(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"),o(),r()}function r(){for(var e=0;e<d.length;e++)d[e].alpha<=0?(t.body.removeChild(d[e].el),d.splice(e,1)):(d[e].y--,d[e].scale+=.004,d[e].alpha-=.013,d[e].el.style.cssText="left:"+d[e].x+"px;top:"+d[e].y+"px;opacity:"+d[e].alpha+";transform:scale("+d[e].scale+","+d[e].scale+") rotate(45deg);background:"+d[e].color+";z-index:99999");requestAnimationFrame(r)}function o(){var t="function"==typeof e.onclick&&e.onclick;e.onclick=function(e){t&&t(),i(e)}}function i(e){var a=t.createElement("div");a.className="heart",d.push({el:a,x:e.clientX-5,y:e.clientY-5,scale:1,alpha:1,color:s()}),t.body.appendChild(a)}function c(e){var a=t.createElement("style");a.type="text/css";try{a.appendChild(t.createTextNode(e))}catch(t){a.styleSheet.cssText=e}t.getElementsByTagName("head")[0].appendChild(a)}function s(){return"rgb("+~~(255*Math.random())+","+~~(255*Math.random())+","+~~(255*Math.random())+")"}var d=[];e.requestAnimationFrame=function(){return e.requestAnimationFrame||e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(e){setTimeout(e,1e3/60)}}(),n()}(window,document);
</script>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<script>
    function secondToDate(second) {
        if (!second) {
            return 0;
        }
        var time = new Array(0, 0, 0, 0, 0);
        if (second >= 365 * 24 * 3600) {
            time[0] = parseInt(second / (365 * 24 * 3600));
            second %= 365 * 24 * 3600;
        }
        if (second >= 24 * 3600) {
            time[1] = parseInt(second / (24 * 3600));
            second %= 24 * 3600;
        }
        if (second >= 3600) {
            time[2] = parseInt(second / 3600);
            second %= 3600;
        }
        if (second >= 60) {
            time[3] = parseInt(second / 60);
            second %= 60;
        }
        if (second > 0) {
            time[4] = second;
        }
        return time;
    }</script>
<script type="text/javascript" language="javascript">
    function setTime() {
        var create_time = Math.round(new Date(Date.UTC(2017, 08, 18, 11, 42, 23)).getTime() / 1000);
        var timestamp = Math.round((new Date().getTime() + 8 * 60 * 60 * 1000) / 1000);
        currentTime = secondToDate((timestamp - create_time));
        currentTimeHtml = 'Running：' + currentTime[0] + '年 ' + currentTime[1] + '天 '
                + currentTime[2] + '时 ' + currentTime[3] + '分 ' + currentTime[4]
                + '秒';
        document.getElementById("htmer_time").innerHTML = currentTimeHtml;
    }    setInterval(setTime, 1000);
</script>
<footer class="footer">
    <div class="top">
        

        <p>
          <span id="busuanzi_container_page_pv">
             [&nbsp;浏览量：&nbsp;<span id="busuanzi_value_page_pv"></span>&nbsp;]
          </span>
        </p>
    </div>
    <div class="bottom">
        <p>
        <span>BingZhenhuang &copy; 2017 - 2020</span>
            <span>
                
                Power by <a href="https://hhardyy.github.io/" target="_blank">zhen On August 8</a> 
            </span>
            <span id="htmer_time" "></span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://yoursite.com/2018/02/02/js中的事件冒泡/&title=《js中的事件冒泡》 — 小方块 - hhardyy.com&pic=http://yoursite.com/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://yoursite.com/2018/02/02/js中的事件冒泡/&title=《js中的事件冒泡》 — 小方块 - hhardyy.com&source=事件是javascript中的核心内容之一，在对事件的应用中不可避免的要涉及到一个重要的概念，那就是事件冒泡，在了解事件冒泡之前，先了解一下事件流" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://yoursite.com/2018/02/02/js中的事件冒泡/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《js中的事件冒泡》 — 小方块 - hhardyy.com&url=http://yoursite.com/2018/02/02/js中的事件冒泡/&via=http://yoursite.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://yoursite.com/2018/02/02/js中的事件冒泡/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>








<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '(•‾̑⌣‾̑•)✧˖°回来看我';
            clearTimeout(titleTime);
        } else {
            document.title = '(゜-゜)つロ欢迎回来';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
